package cn.itcast.crm.service.impl;

import cn.itcast.crm.dao.CustomerRepository;
import cn.itcast.crm.domain.Customer;
import cn.itcast.crm.service.CustomerService;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.util.SystemOutLogger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

/**
 * Created by xbqco on 2018/7/17.
 */
@Service
@Transactional
public class CustomerServiceImpl implements CustomerService{


    // 注入dao
    @Autowired
    private CustomerRepository customerRepository;

    //查询未关联的客户
    @Override
    public List<Customer> findNoAssociationCustomers() {
        // fixedAreaId is null
        return customerRepository.findByFixedAreaIdIsNull();
    }

    //查询已关联到某定区的客户
    @Override
    public List<Customer> findHasAssociationFixedAreaCustomers(String fixedAreaId) {
        // fixedAreaId = ?

        return customerRepository.findByFixedAreaId(fixedAreaId);
    }

    //把客户关联到某定区
    @Override
    public void associationCustomersToFixedArea(String customerIdStr, String fixedAreaId) {


        System.out.println("fixedAreaId:"+fixedAreaId);
        System.out.println("customerIdStr:"+customerIdStr);
        // 经过断点调试，发现action传递过来的customerIdStr有时是"null"
        if (StringUtils.isBlank(customerIdStr) || "null".equals(customerIdStr)) {
            return;
        }

        // 切割字符串 1,2,3
        String[] customerIdArray = customerIdStr.split(",");
        for (String idStr : customerIdArray) {
            try {
                Integer id = Integer.parseInt(idStr);
                customerRepository.updateFixedAreaId(fixedAreaId, id);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void cancel(String noCustomerIds) {
        String[] nocustomerIdArray = noCustomerIds.split(",");
        System.out.println(Arrays.toString(nocustomerIdArray));
        for (String idStr : nocustomerIdArray) {
            try {
                Integer id = Integer.parseInt(idStr);
                customerRepository.updateFixedAreaId(null, id);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public Customer findByTelephone(String telephone) {
        return null;
    }

    @Override
    public Customer login(String telephone, String password) {
        return null;
    }
}


